<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>使用定时器完成下雨特效</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    div {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-color: #474e4d;
      /* 不阻挡其他元素事件触发 */
      pointer-events: none;
    }
    .rain {
      position: absolute;
      width: 2px;
      height: 50px;
      background: linear-gradient(rgba(255, 255, 255, 0.3),rgba(255,255,255,.6));
    }
  </style>
</head>
<body>
  <div></div>
  <script>
    const box = document.querySelector('div');
    let boxHeight = box.clientHeight
    let boxWidth = box.clientWidth
    // 页面大小发生变化时，改变盒子大小
    window.onresize = function(){
        boxHeight = box.clientHeight
        boxWidth = box.clientWidth
    }
    // 每隔一段时间,添加雨滴
    setInterval(function() {
    const rain = document.createElement('div')
    rain.classList.add('rain')
    rain.style.top = 0;
     // 随机刷新雨点位置
    rain.style.left = Math.random() * boxWidth + 'px'
    // 随机雨点透明度
    rain.style.opacity = Math.random();
    box.appendChild(rain);
    // 每隔一段时间,雨水下落
    let race = 1;
    const timer = setInterval(function(){
      if(parseInt(rain.style.top) > boxHeight){
        clearInterval(timer)
        box.removeChild(rain)
      }
      race++;
      rain.style.top = parseInt(rain.style.top) + race + 'px'
     }, 20)
    }, 50)
  </script>
</body>
</html>
